﻿using KouDai.WinPad.Common;
using KouDai.WinPad.Models;
using KouDai.WinPad.ViewModels;
using Windows.Foundation;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using System;

// The Items Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234233

namespace KouDai.WinPad.Views
{
    /// <summary>
    /// A page that displays a collection of item previews.  In the Split Application this page
    /// is used to display and select one of the available groups.
    /// </summary>
    public sealed partial class MainPage : LayoutAwarePage
    {
        private MainPageViewModel _viewModel;

        public MainPage()
        {
            this.InitializeComponent();
        }

        protected override void LoadState(object navigationParameter, System.Collections.Generic.Dictionary<string, object> pageState)
        {
            base.LoadState(navigationParameter, pageState);
            _viewModel = this.DataContext as MainPageViewModel;
        }

        private async void PageTitleTapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
        {
            PopupMenu menu = new PopupMenu();

            if (_viewModel.FatherHotItem == null)
            {
                return;
            }
            foreach (HotEntity model in _viewModel.FatherHotItem.SubCateories)
            {
                if (!_viewModel.CurrentHotItem.OriginalAppName.Equals(model.OriginalAppName))
                {
                    menu.Commands.Add(new UICommand("         " + model.OriginalAppName + "      ", null));
                }
            }
            menu.Commands.Add(new UICommand("         " + _viewModel.CurrentHotItem.OriginalAppName + "      ", null));
      
            var chosenCommand = await menu.ShowForSelectionAsync(GetElementRect((FrameworkElement)sender));

            if (chosenCommand != null)
            {
                if (!_viewModel.CurrentHotItem.OriginalAppName.Equals(chosenCommand.Label.Trim().ToString()))
                {
                    _viewModel.SameLevelNavigate(chosenCommand.Label);
                }
            }
        }

        public static Rect GetElementRect(FrameworkElement element)
        {
            GeneralTransform buttonTransform = element.TransformToVisual(null);
            Point point = buttonTransform.TransformPoint(new Point());
            return new Rect(point, new Size(element.ActualWidth, element.ActualHeight));
        }
    }
}
